﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using VDataAdapter.BlockingQueue;
using System.Collections;
using System.Net;
using VDataAdapter.ClientServer;

namespace VDataAdapter
{
    /// <summary>
    /// Stand between VdataClientThread & PsAdapter 
    /// Do nothing much except start a request handler when receive new Vdata client
    /// </summary>
    public class VndVdataAdapter
    {
        protected PSAdapterThread _psAdapterThread;
        protected VDataClientThread _vdataClientThread;
        TcpListener _serverSocket;
        bool _isRunning;
        VdataRequestHandler _requestHandler;
        CommunicationDataQueue _qMain;

        public VndVdataAdapter()
        {
            _serverSocket = new TcpListener(21845);
            _isRunning = false;
        }               

        /// <summary>
        /// Start listen to tcp
        /// </summary>
        public void Start()
        {
            _requestHandler = new VdataRequestHandler();
            _serverSocket.Start();
            _isRunning = true;
            TcpClient clientSocket;
            ManualResetEvent resetEvent = new ManualResetEvent(false);
            
            // start getting price from server
            _qMain = new CommunicationDataQueue();

            while(_isRunning)
            {
                try
                {
                    clientSocket = default(TcpClient);
                    Console.Write("Awaiting connection..");
                    clientSocket = _serverSocket.AcceptTcpClient();
                    Console.WriteLine(" >> Accept connection from client");
                    if (clientSocket != null)
                    {
                        _requestHandler.ReceiveNewClient(clientSocket, resetEvent);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Error accepting connection");
                }

            }
        }
    }

}
